package com.yaoweigroup.community.ui.my;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONArray;
import org.json.JSONObject;

import com.alipay.android.app.sdk.AliPay;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.hcinfos.gsoo.pay.Keys;
import com.hcinfos.gsoo.pay.Rsa;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.MyDsicountOrderAdapter;
import com.yaoweigroup.community.adapter.MyOrderAdapter;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.dialog.DialogCallBack;
import com.yaoweigroup.community.enity.DiscountOrder;
import com.yaoweigroup.community.enity.OrderInfo;
import com.yaoweigroup.community.enity.UserInfo;
import com.yaoweigroup.community.interfaze.Callback;
import com.yaoweigroup.community.ui.bm.OrderSubmitActivity;
import com.yaoweigroup.community.util.ApkDownloadUtil;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.LoginUtil;
import com.yaoweigroup.community.util.SharePreferenceUtil;
import com.yaoweigroup.community.util.UtilHttp;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 我的优惠信息
 * 
 * @author xi
 * 
 */
public class MyDiscountActivity extends Activity implements OnClickListener,
		Callback {

	private RelativeLayout left_rl;
	private PullToRefreshListView listView;
	private MyDsicountOrderAdapter adapter;
	private List<DiscountOrder> list;

	public final int ORDER_SUCCESS = 0x2210;
	public final int ORDER_FAIL = ORDER_SUCCESS + 1;
	public final int CANCEL_SUCCESS = ORDER_SUCCESS + 2;
	public final int CANCEL_FAIL = ORDER_SUCCESS + 3;
	public final int NEED_LOGIN = ORDER_SUCCESS + 4;
	public final int RQF_PAY = ORDER_SUCCESS + 5;
	private ProgressBar progress;

	private SharePreferenceUtil util;
	private ObjectMapper mapper;

	private ImageView error_iv;

	private Dialog dialog;
	
	private TextView center_tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_order);

		dialog = DialogUtil.createWaitDialog(this, "正在取消中...");
		mapper = new ObjectMapper();
		util = new SharePreferenceUtil(this, Constant.prf);
		progress = (ProgressBar) findViewById(R.id.progress);
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);

		list = new ArrayList<DiscountOrder>();
		listView = (PullToRefreshListView) findViewById(R.id.listView);
		adapter = new MyDsicountOrderAdapter(this, list);
		adapter.setCallback(this);
		listView.setAdapter(adapter);
		error_iv = (ImageView) findViewById(R.id.error_iv);
		
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("我的优惠信息");
		listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				error_iv.setVisibility(View.GONE);
				pageNo = 1;
				list.clear();
				adapter.setDataChange(list);
				progress.setVisibility(View.VISIBLE);
				obtainData();
			}
		});
		obtainData();
	}

	private void obtainData() {
		user = (UserInfo) util.loadObject("user");
		if (user != null) {
			listOrder(user.getUid());
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		}
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			dialog.dismiss();
			switch (msg.what) {
			case ORDER_FAIL:
				error_iv.setVisibility(View.VISIBLE);
				progress.setVisibility(View.GONE);
				listView.onRefreshComplete();
				break;
			case ORDER_SUCCESS:
				if (orders != null && orders.size() > 0) {
					list.addAll(orders);
				}
				if (list.size() == 0) {
					error_iv.setVisibility(View.VISIBLE);
				}
				Collections.reverse(list);
				adapter.setDataChange(list);
				progress.setVisibility(View.GONE);
				listView.onRefreshComplete();
				break;
			case CANCEL_FAIL:
				Toast.makeText(MyDiscountActivity.this, "取消失败", 500).show();
				break;
			case CANCEL_SUCCESS:
				list.clear();
				adapter.setDataChange(list);
				obtainData();
				break;
			case LoginUtil.LOGIN_FAIL:
				progress.setVisibility(View.GONE);
				break;
			case LoginUtil.LOGIN_SUCCESS:
				if (isCancel) {
					cancelOrder(orderId);
				} else {
					obtainData();
				}
				break;
			case NEED_LOGIN:
				LoginUtil.isLoginSuccess(MyDiscountActivity.this, handler,
						mapper);
				break;
			case RQF_PAY:

				break;
			}
		};
	};

	/**
	 * 获取订单列表
	 */
	private UserInfo user;
	private int pageSize = 10;
	private int pageNo = 1;
	private List<DiscountOrder> orders;

	private void listOrder(String uid) {
		orders = new ArrayList<DiscountOrder>();
		user = (UserInfo) util.loadObject("user");
		progress.setVisibility(View.VISIBLE);
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", user.getUid());
		jsonUtil.add("pageNo", pageNo + "");
		jsonUtil.add("pageSize", pageSize + "");
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.queryPreferentialOrder,
				params, new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						try {
							JSONObject obj = new JSONObject(responseInfo.result);
							int state = obj.getInt("state");
							if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else if (state == 200) {
								// String data = obj.getString("data");
								// orders = mapper.readValue(data,
								// new TypeReference<List<OrderInfo>>() {
								// });
								JSONArray dataArray = obj.getJSONArray("data");
								for (int i = 0; i < dataArray.length(); i++) {

									JSONObject dataObj = dataArray
											.getJSONObject(i);
									int id = dataObj.getInt("Id");
									String consignee = dataObj
											.getString("consignee");
									String orderNum = dataObj
											.getString("orderNum");
									String phoneNum = dataObj
											.getString("phoneNum");
									String createDate = dataObj
											.getString("createDate");
									int payState = dataObj.getInt("state");
									JSONArray array = dataObj
											.getJSONArray("details");
									String preferentialName = "";
									String preferentialPrice = "";
									String preferentialCount = "";
									if (array.length() > 0) {
										preferentialName = array.getJSONObject(
												0)
												.getString("preferentialName");
										preferentialPrice = array
												.getJSONObject(0).getString(
														"preferentialPrice");
										preferentialCount = array
												.getJSONObject(0).getString(
														"preferentialCount");
									}

									DiscountOrder order = new DiscountOrder(id,
											consignee, preferentialName,
											preferentialPrice,
											preferentialCount, orderNum,
											phoneNum, createDate, payState);
									orders.add(order);
								}
								handler.sendEmptyMessage(ORDER_SUCCESS);
							} else {
								handler.sendEmptyMessage(ORDER_FAIL);
							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(ORDER_FAIL);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(ORDER_FAIL);
					}

				});
	}

	/**
	 * 取消订单
	 */
	private boolean isCancel = false;
	private String orderId = null;

	private void cancelOrder(String orderNum) {
		dialog.show();
		isCancel = true;
		UserInfo user = (UserInfo) util.loadObject("user");
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", user.getUid());
		jsonUtil.add("orderNum", orderNum);
		jsonUtil.add("canceldes", "不想要了");
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString(), "UTF-8");
		} catch (Exception e) {
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.cancelPreferentialOrder,
				params, new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else if (state == 200) {
								handler.sendEmptyMessage(CANCEL_SUCCESS);
							} else {
								handler.sendEmptyMessage(CANCEL_FAIL);

							}
						} catch (Exception e) {
							handler.sendEmptyMessage(CANCEL_FAIL);
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(CANCEL_FAIL);

					}

				});
	}

	@Override
	public void callback(String id, int tagId, double price) {
		orderId = id;
		switch (tagId) {
		case 0:
			DialogUtil.versionDialog(MyDiscountActivity.this, "是否取消确定",
					new DialogCallBack() {

						@Override
						public void viewClick() {
						}

						@Override
						public void ok() {
							cancelOrder(orderId);
						}

						@Override
						public void init(Object obj) {

						}

						@Override
						public void cancel() {

						}
					}, "确定", "取消");

			break;
		case 1:
			pay(id, price);
			break;
		}
	}

	// 取消订单

	/**
	 * 支付宝支付模块
	 */
	private void pay(String orderNum, double total) {
		String info = getOrderInfo(orderNum, total);
		String sign = Rsa.sign(info, Keys.PRIVATE);
		sign = URLEncoder.encode(sign);
		info += "&sign=\"" + sign + "\"&" + getSignType();
		final String orderInfo = info;
		new Thread() {
			public void run() {
				AliPay alipay = new AliPay(MyDiscountActivity.this, handler);

				// 设置为沙箱模式，不设置默认为线上环境
				// alipay.setSandBox(true);
				String result = alipay.pay(orderInfo);
				Message msg = handler.obtainMessage();
				msg.what = RQF_PAY;
				msg.obj = result;
				handler.sendMessage(msg);
				LogUtil.d("wxf", "result = " + result);
			}
		}.start();
	}

	private double total = 0;

	private String getOrderInfo(String orderNum, double total) {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(orderNum);
		sb.append("\"&subject=\"");
		sb.append("订单");
		sb.append("\"&body=\"");
		sb.append("dfdsfdsfdsf");
		sb.append("\"&total_fee=\"");
		sb.append(total + "");
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder
				.encode("http://www.smartcity.sh/Shared/notify_url"));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
